package pct.page;

import java.util.LinkedList;
import java.util.Map;

import org.apache.struts2.interceptor.SessionAware;

import pct.database.PcServiceImpl;
import pct.entity.Group;
import pct.manage.StatusManager;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;

@SuppressWarnings({ "serial"})
public class ChangePage extends ActionSupport implements
		Preparable, SessionAware {
	private PcServiceImpl pcService = new PcServiceImpl();
	private Map<String, Object> session;
	
	public String execute() {
		StatusManager sm = (StatusManager) session.get("status");
		PageFilter pf = new PageFilter();
		int currentPageNumber = sm.getCurrentPage();	
		
		switch(sm.getPageType()) {
		case 1:
			// viewing groups
			int pageSize = pf.getGroupPages(sm.getCurrentUser());
			if(currentPageNumber+1 <= pageSize){
				LinkedList<Group> relatedGroups = pf.getTargetedPageGroups(sm.getCurrentUser(), currentPageNumber+1);
				if (relatedGroups != null) {
					for (Group i : relatedGroups) {
						i.setTopicNumber(pcService.retrieveTopicNumber(i
								.getGroupName()));
						i.setPostNumber(pcService.retrievePostNumber(i
								.getGroupName()));
					}
				}
				sm.setRelatedGroups(relatedGroups);
				sm.setCurrentPage(currentPageNumber+1);
			}
			else{
				LinkedList<Group> relatedGroups = pf.getFirstPageGroups(sm.getCurrentUser());
				if (relatedGroups != null) {
					for (Group i : relatedGroups) {
						i.setTopicNumber(pcService.retrieveTopicNumber(i
								.getGroupName()));
						i.setPostNumber(pcService.retrievePostNumber(i
								.getGroupName()));
					}
				}
				sm.setRelatedGroups(relatedGroups);
				sm.setCurrentPage(1);
			}
			break;
		case 2:
			break;
		case 3:
			break;
		case 11:
			break;
		case 12:
			// viewing topics by search
			
			break;
		case 13:
			break;
		}
		session.put("status", sm);
		return SUCCESS;
	}
	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	@Override
	public void prepare() throws Exception {
		pcService.connectDB();
	}
}
